<template>
  <a-card class="card">
    <template #title>
      <slot name="title"></slot>
    </template>
    <template #extra>
      <a-tag
        v-if="userInfo.accountType == 'ADMIN' && filterOption.kmdm"
        :color="
          Data.applyOverInfo?.applyState == 'AUDIT'
            ? '#F97316'
            : Data.applyOverInfo?.applyState == 'REJECT'
            ? '#DC2626'
            : Data.applyOverInfo?.applyState == 'PASS'
            ? '#10C0B6'
            : ''
        "
        :title="Data.applyOverInfo?.applyRemark"
      >
        {{ Data.applyOverInfo?.applyStatTest }}
      </a-tag>
      <a-button
        class="mr-8px"
        type="primary"
        v-if="userInfo.accountType == 'ADMIN' && !zpDataFlag && filterOption.kmdm"
        :disabled="Data.applyOverInfo?.applyState == 'AUDIT'"
        @click="handleBeforeSubmit"
      >
        代组长上报评阅完成
      </a-button>
      <scoreStat
        v-if="userInfo.accountType == 'ADMIN' && filterOption.kmdm"
        v-model:spinning="Data.spinning"
        :zpDataFlag="zpDataFlag"
        :record="{
          kmdm: filterOption.kmdm,
          kmmc: filterOption.kmmc,
        }"
        @handleClick="handleClick"
      />

      <a-button
        class="mr-8px"
        :disabled="!filterOption.kmdm || Data.applyOverInfo?.applyState !== 'AUDIT'"
        type="primary"
        v-if="userInfo.accountType == 'ADMIN'"
        @click="handleAudit"
      >
        评阅完成审核
      </a-button>

      <slot name="extra"></slot>
    </template>
    <a-row align="top" justify="space-between">
      <div class="w-full">
        <SearchGroup
          :label-option="Data.labelOption"
          @handleSearch="resetData(loadData)"
          @handleReset="resetData(reset)"
          v-model:searchOption="filterOption"
        />

        <km-statis
          :updeatObjTime="Data.updeatObjTime"
          :kmdm="filterOption.kmdm"
          :zpDataFlag="zpDataFlag"
        />

        <a-table
          :pagination="false"
          :columns="creterColumns()"
          :data-source="list"
          size="small"
          :loading="loading"
          :scroll="{ x: 1450 }"
          :row-class-name="
            (record, index) => {
              if (record?.hasChildFlag) return 'font-bold text-lg bg-gray-200'
              if (!record?.statistics?.pywcRate) return 'bg-red-200'
              if (record?.statistics?.pywcRate < 1) return 'bg-orange-200'
              return 'bg-green-200'
            }
          "
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.dataIndex === 'pywc' && !record?.hasChildFlag">
              <div class="py-5">
                <a-progress
                  stroke-color="#10C0B6"
                  :percent="Number(record?.statistics?.pywcRate || 0) * 100"
                  :format="percent => `${percent.toFixed(2)}%`"
                />
              </div>
              <span>
                <i class="text-green-600"> {{ record?.statistics?.pywcNum || 0 }} </i>/
                {{ record?.statistics?.ysmKsNum || 0 }}
              </span>
            </template>
            <template v-if="column.dataIndex === 'pyz' && !record?.hasChildFlag">
              <div class="py-5">
                <a-progress
                  stroke-color="#F97316"
                  :percent="Number(record?.statistics?.pyzRate || 0) * 100"
                  :format="percent => `${percent.toFixed(2)}%`"
                />
              </div>
              <span>
                <i class="text-orange-600"> {{ record?.statistics?.pyzNum || 0 }} </i> /
                {{ record?.statistics?.ysmKsNum || 0 }}
              </span>
            </template>
            <template v-if="column.dataIndex === 'wpy' && !record?.hasChildFlag">
              <div class="py-5">
                <a-progress
                  stroke-color="#DC2626"
                  :percent="Number(record?.statistics?.wpyRate || 0) * 100"
                  :format="percent => `${percent.toFixed(2)}%`"
                />
              </div>
              <span>
                <i class="text-red-600"> {{ record?.statistics?.wpyNum || 0 }} </i> /
                {{ record?.statistics?.ysmKsNum || 0 }}
              </span>
            </template>
          </template>
        </a-table>
      </div>

      <echart-assembly
        v-if="false"
        :infoList="list"
        :kmdm="filterOption.kmdm"
        :zpDataFlag="zpDataFlag"
      />
    </a-row>

    <!-- 审核 -->
    <auditOver
      v-model:auditVisible="Data.auditVisible"
      :auditRow="Data.auditRow"
      @success="aboutSuccess"
    />

    <!-- 申请 -->
    <applyOver v-model:applyVisible="Data.applyVisible" @success="handleSubmit" />
  </a-card>
</template>

<script setup lang="ts">
import { creterColumns } from '/@/views/home/index/index'
import echartAssembly from '/@/views/home/index/components/echartAssembly.vue'
import kmStatis from '/@/views/home/index/components/kmStatis.vue'
import { onMounted, reactive, computed } from 'vue'
import { getKmSimpAlleList } from '/@/api/organization/subjectManage'
import {
  getcommonKmSummarySt,
  getKmPyProcess,
  getPyOverApplyKmdm,
  setkmPyOverApply,
} from '/@/api/teacher'
import auditOver from '/@/views/organizationalManagement/subjectManage/auditOver.vue'
import applyOver from '/@/views/examination-audit/review-task/applyOver.vue'
import scoreStat from '/@/views/home/index/components/scoreStat.vue'
import { useList } from '/@/hooks/web/useList'
import { useUserStore } from '/@/store/modules/user'
import { getDictionaryList } from '/@/views/teacher/home/index'
import { useMessage } from '/@/hooks/web/useMessage'
const { createMessage } = useMessage()

const userStore = useUserStore()
const userInfo = computed<any>(() => userStore.getUserInfo)

const props = defineProps({
  // 科目
  zpDataFlag: {
    type: Boolean,
    default: false,
  },
})

const { list, loading, loadData, filterOption, reset } = useList(getcommonKmSummarySt, {
  immediate: false,
  defaultFilterOption: <any>{
    zpDataFlag: props.zpDataFlag,
  },
  transformFn(e) {
    if (e.code == 200) {
      let data = e.data.filter(
        item => item.tmlx !== '单项选择题' && item.tmlx !== '多项选择题' && item.tmlx !== '判断题'
      )
      return {
        code: 200,
        data,
        msg: '查询成功',
      }
    } else return e
  },
  requestSuccess(e) {
    getKmApplyOverview()
  },
})

const emit = defineEmits(['changeFun'])

const Data = reactive({
  auditVisible: false,
  auditRow: {
    pyOverApplyInfo: {},
  },
  labelOption: [
    {
      labelWidth: 50,
      key: 'kmdm',
      type: 'Select',
      name: '科目',
      selectOption: [],
      fieldNames: { label: 'kmmc', value: 'kmdm' },
    },
  ],
  spinning: false,
  applyOverInfo: {},
  auditList: [],
  applyVisible: false,
  updeatObjTime: new Date().getTime(),
} as any)

async function getKmList() {
  let { code, data } = await getKmSimpAlleList({
    pageSize: 0,
  })
  if (code == 200) {
    data.forEach(item => (item.kmmc = `${item.kmdm}(${item.kmmc})`))
    Data.labelOption[0].selectOption = data.sort((a, b) => a.kmdm - b.kmdm)
  }
}

function aboutSuccess() {
  getKmApplyOver(filterOption.value?.kmdm)
  loadData()
}

function resetData(callback: Function) {
  emit('changeFun', filterOption.value?.kmdm)
  if (filterOption.value?.kmdm) {
    callback()
    getKmApplyOver(filterOption.value.kmdm)
    Data.updeatObjTime = new Date().getTime()
    return
  }
  list.value = []
}

function getKmApplyOverview() {
  if (list.value?.length == 0) return
  getKmPyProcess({
    kmdm: filterOption.value?.kmdm,
    zpDataFlag: props.zpDataFlag,
  }).then(res => {
    if (res.code == 200)
      for (let i = 0; i < list.value.length; i++) {
        list.value[i].statistics = {}
        for (let j = 0; j < res.data.length; j++) {
          if (list.value[i].stId == res.data[j].stId) {
            list.value[i].statistics = res.data[j]
            break
          }
        }
      }
  })
}

function handleAudit() {
  Data.auditRow = {
    kmdm: filterOption.value?.kmdm,
    pyOverApplyInfo: {
      ...Data.applyOverInfo,
    },
  }
  Data.auditVisible = true
}

/**
 * 上报评阅完成
 */
async function handleSubmit(applyRemark) {
  const { code, message } = await setkmPyOverApply({
    kmdm: filterOption.value?.kmdm,
    zpDataFlag: props.zpDataFlag,
    applyRemark,
  })
  if (code == 200) {
    createMessage.success(message)
    getKmApplyOver(filterOption.value?.kmdm)
  } else createMessage.error(message)
}

/**
 * 获取科目评阅进度信息（是否评完）
 */
async function getKmApplyOver(kmdm) {
  Data.applyOverInfo = {}
  if (!kmdm || kmdm === '0') return
  const { code, data } = await getPyOverApplyKmdm({
    kmdm,
    zpDataFlag: props.zpDataFlag,
  })
  if (code == 200) {
    Data.applyOverInfo = data || {}
    Data.applyOverInfo.applyStatTest =
      Data.auditList?.find(item => item.value === data?.applyState)?.label || '未上报评阅完成状态'
  }
}

function handleBeforeSubmit() {
  Data.applyVisible = true
}

function handleClick() {
  loadData()
  Data.updeatObjTime = new Date().getTime()
}

onMounted(async () => {
  getKmList()
  Data.auditList = (await getDictionaryList('audit')) || []
})
</script>
